package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.SecUserDTO;
import com.example.exception.ServiceException;
import com.example.mapper.SecUserMapper;
import com.example.model.SecUser;
import com.example.service.SecUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liheng
 * @since 2021-05-20
 */
@Service
public class SecUserServiceImpl extends ServiceImpl<SecUserMapper, SecUser> implements SecUserService {
    private final SecUserMapper secUserMapper;

    @Autowired
    public SecUserServiceImpl(SecUserMapper secUserMapper) {
        this.secUserMapper = secUserMapper;
    }


    /**
     * 新增管理员账号
     *
     * @param dto 管理员信息
     * @return 新增结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdateUser(SecUserDTO dto) {
        if (Objects.isNull(dto.getId())) {
            // 检查登陆账号是否存在
            SecUser sysUser = secUserMapper.selectOne(new LambdaQueryWrapper<SecUser>()
                    .eq(SecUser::getAccount, dto.getAccount()));
            if (Objects.nonNull(sysUser)) {
                throw new ServiceException("该账号已存在，请勿重复注册");
            }
            if (StringUtils.isNotBlank(dto.getPassword())) {
                dto.setPassword(dto.getPassword());
            }
            secUserMapper.insert(dto);
        } else {
            if (dto.getId().equals(1)) {
                return;
            }
            dto.setAccount(null);
            if (StringUtils.isNotBlank(dto.getPassword())) {
                dto.setPassword(dto.getPassword());
            }
            secUserMapper.updateById(dto);
        }
    }
}
